<!-- ERC-设备巡检-巡检任务 -->
<template>
  <div>
    <div v-show="isMain" class="inspect-wrap-common">
      <px-form ref="formRef" class="custom-form-ui inspect-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="计划编号">
              <px-input
                v-model="queryParams.planNo"
                placeholder="请输入"
                maxlength="50"
                @blur="queryParams.planNo = $event.target.value.trim()"
                clearable
                @keyup.enter="getDataByNewQuery"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="getDataByNewQuery">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="任务名称">
              <px-input
                v-model="queryParams.taskName"
                placeholder="输入名称/编号"
                maxlength="50"
                clearable
                @blur="queryParams.taskName = $event.target.value.trim()"
                @keyup.enter="getDataByNewQuery"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="getDataByNewQuery">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <FactoryArea :factoryArea="queryParams.factoryAreaCode" @changeFactoryArea="changeFactoryArea" />
          </px-col>
          <px-col :span="6">
            <TaskSource :taskType="queryParams.taskType" @changeTaskSource="changeTaskSource" />
          </px-col>
        </px-row>
        <px-row :gutter="16">
          <px-col :span="6">
            <TaskStatus :taskStatus="queryParams.taskStatus" @changeTaskStatus="changeTaskStatus" />
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="getDataByNewQuery">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div v-has="'ERC_INSPECT_TASK_ADD'" class="inspect-table-btn">
        <px-button v-has="'ERC_INSPECT_TASK_ADD'" style="margin-right: 8px" type="primary" @click="handleAdd">新增巡检任务</px-button>
      </div>
      <px-table :data="tableData" class="inspect-table" size="small" height="calc(100vh - 350px)" border>
        <px-table-column label="序号" min-width="50" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <template v-for="(item, index) in tableColumns" :key="index">
          <px-table-column
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template v-if="item.prop === 'taskNo'" #default="scope">
              <span v-if="isHasPermission('ALL_EQUIP_INSPECT_TASK_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">{{
                scope.row.taskNo
              }}</span>
              <span v-else>{{ scope.row.taskNo }}</span>
            </template>
            <template v-else-if="item.type === 'status'" #default="scope">
              <!-- <div class="status">
                <div class="circle" :style="{ backgroundColor: `${TAG_CONFIG[scope.row.taskStatus]?.color}` }" />
                <p :style="{ color: `${TAG_CONFIG[scope.row.taskStatus]?.color}` }">{{ scope.row.taskStatusDesc }}</p>
                <p v-if="scope.row.timeOut === 1" :style="{ color: '#EF4444', marginLeft: '4px' }">超期</p>
              </div> -->
              <px-tag class="ml-2" :type="tagArr[scope.row['taskStatus']]"
                >{{ scope.row["taskStatusDesc"] }}{{ scope.row.timeOut === 1 ? "(超期)" : "" }}</px-tag
              >
            </template>
            <template v-else #default="scope">
              {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
            </template>
          </px-table-column>
        </template>

        <px-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_TABLE_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.taskStatus === 0" content="取消原因" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_TABLE_VIEW'" link type="primary" icon="ChatLineSquare" @click="handleShowCancelReason(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="showActionBtn(scope.row, 'ERC_INSPECT_TASK_EXAMINE_WITHDRAW', 1)" content="撤回审核" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_EXAMINE_WITHDRAW'" link type="primary" icon="Rollback" @click="handleTaskBack(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="showActionBtn(scope.row, 'ERC_INSPECT_TASK_CANCEL', 3)" content="取消任务" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_CANCEL'" link type="primary" icon="CloseCircle" @click="handleCancel(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="showActionBtn(scope.row, 'ERC_INSPECT_TASK_TODO', 1)" content="执行任务" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_TODO'" link type="primary" icon="DocumentChecked" @click="handleTodo(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="showActionBtn(scope.row, 'ERC_INSPECT_TASK_EXAMINE', 2)" content="审核" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_EXAMINE'" link type="primary" @click="handleAccept(scope.row)">
                <px-icon>
                  <Stamp />
                </px-icon>
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="showActionBtn(scope.row, 'ERC_INSPECT_TASK_TRANSFER_REVIEW', 1)" content="转审" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_TRANSFER_REVIEW'" link type="primary" @click="handleReview(scope.row)">
                <px-icon>
                  <Transfer />
                </px-icon>
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="scope.row.taskStatus === 3" content="导出" placement="top">
              <px-button v-has="'ERC_INSPECT_TASK_EXPORT'" link type="primary" @click="handleExport(scope.row)"
                ><px-icon><DownloadPx /></px-icon>
              </px-button>
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspect-table-pagination"
        :total="total"
        @pagination="getDataByNewQuery"
      />
    </div>
    <!-- 新增巡检任务 -->
    <AddInspectTask v-if="isAdd" v-model:is-main="isMain" v-model:is-add="isAdd" />
    <!-- 巡检任务详情 -->
    <InspectTaskDetail v-if="isView" ref="taskDetailRef" :moduleName="moduleName" :data="taskData" @backMainPage="backMainPage" />
    <!-- 审核 -->
    <SubmitCheckResult
      v-if="submitCheckResultVisible"
      v-model:dialogVisible="submitCheckResultVisible"
      :moduleName="moduleName"
      :data="taskData"
      @refresh="queryTable"
    />
    <!-- 转审 -->
    <ChangeAcceptor v-if="changeAcceptorVisible" v-model:dialogVisible="changeAcceptorVisible" :data="taskData" @refresh="queryTable" />
    <!-- 取消任务 -->
    <CancelInspectTask v-if="cancelInspectVisible" v-model:dialogVisible="cancelInspectVisible" :data="taskData" @refresh="queryTable" />
    <!-- 任务取消原因 -->
    <CancelReason v-if="reasonVisible" v-model:dialogVisible="reasonVisible" :data="taskData" />
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_INSPECT_TASK"
});
import { getFileModelName, queryTaskTable, taskBack } from "@/api/erc/inspectTask";
import Stamp from "@/assets/svg/operation/stamp.svg?component";
import Transfer from "@/assets/svg/operation/transfer.svg?component";
import { isHasPermission } from "@/utils/auth";
import { stringTrimOfParams } from "@/utils/common";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, nextTick, onBeforeMount, onMounted, reactive, ref, toRefs, watch } from "vue";
import { useRoute } from "vue-router";
import { FactoryArea } from "../components/index";
import AddInspectTask from "./components/AddInspectTask.vue";
import CancelInspectTask from "./components/CancelInspectTask.vue";
import CancelReason from "./components/CancelReason.vue";
import ChangeAcceptor from "./components/ChangeAcceptor.vue";
import InspectTaskDetail from "./components/InspectTaskDetail.vue";
import SubmitCheckResult from "./components/SubmitCheckResult.vue";
import TaskSource from "./components/TaskSource.vue";
import TaskStatus from "./components/TaskStatus.vue";
import { TAG_CONFIG, USER_ROLE } from "./config";

const route = useRoute();
const tagArr = ["info", "warning", "primary", "success", "success", "primary"];
const formRef = ref();
const state = reactive<any>({
  isMain: true, // 主页面true 其他页面false
  isView: false, // 详情true 其他false
  isAdd: false, // 新增编辑true 其他false
  taskData: "",
  userId: "",
  queryParams: {
    planNo: "",
    taskName: "",
    factoryAreaCode: "",
    taskStatus: "",
    taskType: "",
    pageNum: 1,
    pageSize: 20
  },
  formValue: {
    planNo: "",
    taskName: "",
    factoryAreaCode: "",
    taskStatus: "",
    taskType: "",
    pageNum: 1,
    pageSize: 20
  },
  total: 0,
  tableColumns: [
    { prop: "taskNo", label: "任务(工单)编号", minWidth: "140", showOverflowTooltip: true, fixed: "left" },
    { prop: "planNo", label: "所属计划编号", minWidth: "140", showOverflowTooltip: true },
    { prop: "taskName", label: "任务名称", minWidth: "150", showOverflowTooltip: true },
    { prop: "taskTypeDesc", label: "任务类型", minWidth: "80", showOverflowTooltip: true },
    { prop: "startTime", label: "任务开始时间", minWidth: "100", showOverflowTooltip: true },
    { prop: "endTime", label: "任务结束时间", minWidth: "100", showOverflowTooltip: true },
    { prop: "factoryAreaDesc", label: "地块", minWidth: "170", showOverflowTooltip: true },
    { prop: "taskType", label: "状态", minWidth: "120", type: "status", showOverflowTooltip: true },
    { prop: "checkGroupDesc", label: "巡检组", minWidth: "130", showOverflowTooltip: true },
    { prop: "submitTime", label: "最后执行时间", minWidth: "100", showOverflowTooltip: true }
  ],
  tableData: [],
  detailPageType: "add",
  submitCheckResultVisible: false,
  changeAcceptorVisible: false,
  cancelInspectVisible: false,
  reasonVisible: false,
  planNo: "",
  moduleName: ""
});
const {
  isView,
  userId,
  moduleName,
  isMain,
  taskData,
  isAdd,
  queryParams,
  formValue,
  tableColumns,
  total,
  tableData,
  submitCheckResultVisible,
  changeAcceptorVisible,
  cancelInspectVisible,
  reasonVisible
} = toRefs(state);
const taskDetailRef = ref<InstanceType<typeof InspectTaskDetail> | null>(null);
// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getFileModelName();
  moduleName.value = data;
};
// 页面本身的值
const { proxy }: any = getCurrentInstance();
const handleExport = async data => {
  const params = {
    // ...data,
    taskNo: data.taskNo,
    taskName: data.taskName
  };
  await proxy.download("post", "/erc/api/v1/checkTask/export", params, data.taskName + ".xlsx");
  PxMessage.success("任务已导出");
};
onBeforeMount(() => {
  getModuleNameValue();
  const {
    query: { taskNo }
  } = route;
  if (taskNo) {
    // 1、reffer, taskNo存在——表明来自其他页面，访问任务详情页
    isMain.value = false;
    isView.value = true;
  } else {
    // 2、reffer, taskNo不存在——表明访问任务列表页
    queryTable();
  }
});
// 进入页面时触发
onMounted(() => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
});
// 分页查询任务列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(formValue.value));
  const data = await queryTaskTable(stringTrimOfParams(params));
  tableData.value = data?.data;
  total.value = data?.total;
};
// 改变查询条件并获取人物列表
const getDataByNewQuery = () => {
  formValue.value = JSON.parse(JSON.stringify(queryParams.value));
  queryTable();
};

// 重置筛选条件和巡检清单
const resetTable = async () => {
  queryParams.value = {
    planNo: "",
    taskName: "",
    factoryAreaCode: "",
    taskStatus: "",
    taskType: "",
    pageNum: 1,
    pageSize: 20
  };
  formRef.value.resetFields();
  getDataByNewQuery();
};
// 地块改变
const changeFactoryArea = (value: any) => {
  queryParams.value.factoryAreaCode = value;
};
// 任务来源改变
const changeTaskSource = (value: any) => {
  queryParams.value.taskType = value;
};
// 任务状态改变
const changeTaskStatus = (value: any) => {
  queryParams.value.taskStatus = value;
};
// 通过任务状态判断是否应该显示指定操作按钮
const showActionBtnByTaskStatus = (status: number, action: string) => {
  const statusConfig = TAG_CONFIG[status];
  if (statusConfig) {
    const flag = statusConfig.actions.includes(action);
    return flag;
  } else {
    return false;
  }
};
const showActionBtn = (data: any, action: string, type: number) => {
  const flag = showActionBtnByTaskStatus(data.taskStatus, action);
  if (type === 1) {
    // 执行人
    return flag && USER_ROLE.isoperator(data);
  }
  if (type === 2) {
    // 验收人
    return flag && USER_ROLE.isAccepter(data);
  }
  if (type === 3) {
    // 计划创建人
    return flag && USER_ROLE.isCreater(data);
  }
  // 审核发起人
  return flag && USER_ROLE.isExecutor(data);
};
// 关闭所有页面
const handleClose = () => {
  isAdd.value = false;
  isMain.value = false;
  isView.value = false;
};
//返回主页面
const backMainPage = () => {
  handleClose();
  isMain.value = true;
};
// 跳转详情
const handleView = (value: any) => {
  handleClose();
  taskData.value = value;
  isView.value = true;
};
// 新增巡检任务
const handleAdd = () => {
  handleClose();
  isAdd.value = true;
};
// 撤回审核
const handleTaskBack = (row: any) => {
  const { taskNo } = row;
  PxMessageBox.confirm(`确认撤回审核吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await taskBack(taskNo);
      PxMessage.success("撤回成功");
      queryTable();
    })
    .catch(() => {});
};
// 取消任务
const handleCancel = (row: any) => {
  taskData.value = row;
  cancelInspectVisible.value = true;
};
// 取消任务原因
const handleShowCancelReason = (row: any) => {
  taskData.value = row;
  reasonVisible.value = true;
};
// 执行任务
const handleTodo = (row: any) => {
  handleView(row);
  nextTick(() => {
    taskDetailRef.value?.gotoTaskFormPage();
  });
};
// 审核
const handleAccept = (row: any) => {
  taskData.value = row;
  submitCheckResultVisible.value = true;
};
// 转审
const handleReview = (row: any) => {
  changeAcceptorVisible.value = true;
  taskData.value = row;
};
watch(
  () => isMain.value,
  () => {
    if (isMain.value) {
      queryTable();
    }
  }
);
</script>

<style lang="scss" scoped>
@import url("../scss/table-list.scss");

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
